package com.ar.network;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Handler;

public class SOAPConnector extends Thread {
	private static final String NAMESPACE = "http://service.ar.com/";
	private static final String URL = "http://192.168.1.10:8080/StudyService/services/StudyServicePort?wsdl";
	private static final String SOAP_ACTION = "";
	private static final String METHOD_NAME = "onRequest";
	private static final String PARAMETER = "arg0";
	private int timeOut;
	private boolean isTimeOut;

	private Handler mHandler;
	private String jsonRequest;

	public SOAPConnector(String jsonRequest) {
		this.jsonRequest = jsonRequest;
		mHandler = new Handler();
		timeOut = NetworkUtility.DEFAULT_TIME_OUT * 1000;
		isTimeOut = false;
	}

	public SOAPConnector() {
		mHandler = new Handler();
		timeOut = NetworkUtility.DEFAULT_TIME_OUT * 1000;
		isTimeOut = false;
	}

	private OnResponseListener responser;

	public void setOnResponseListener(OnResponseListener responser) {
		this.responser = responser;
		mHandler = new Handler();
	}

	@Override
	public void run() {
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, timeOut);
		PropertyInfo lnameProp = new PropertyInfo();
		lnameProp.setName(PARAMETER);
		lnameProp.setValue(jsonRequest);
		lnameProp.setType(String.class);
		request.addProperty(lnameProp);
		try {
			androidHttpTransport.call(SOAP_ACTION, envelope);
		} catch (IOException e) {
			e.printStackTrace();
			isTimeOut = true;
			mHandler.post(new Runnable() {
				
				@Override
				public void run() {
					if (responser != null) responser.onRequestTimeOut();
				}
			});
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
		if (!isTimeOut) {
			try {
			final SoapPrimitive response = (SoapPrimitive) envelope
					.getResponse();
			mHandler.post(new Runnable() {

				@Override
				public void run() {
					if (responser != null)
						responser.onResponse(response.toString());
				}
			});

		} catch (SoapFault e) {
			e.printStackTrace();
		}
		}
	}

	public void startRequest() {
		
		this.start();
	}

	public void setTimeOut(int timeOut) {
		this.timeOut = timeOut;
	}

}
